﻿using NLog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;

namespace PowerBooking.RSE.Domain.Behaviors
{
    [AttributeUsage(AttributeTargets.Class, Inherited = true)]
    public class ErrorHandlerBehaviorAttribute : Attribute, IServiceBehavior
    {
        public readonly ErrorHandler ErrorHandler;
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public ErrorHandlerBehaviorAttribute()
        {
            ErrorHandler = new ErrorHandler(error =>
                {
                    logger.ErrorException(error.Message, error);
                    return false;
                },
                error =>
                {
                    return error.Message;
                });
        }

        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters) { }
        
        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
            {
                dispatcher.ErrorHandlers.Add(ErrorHandler);
            }
        }

        public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase) { }
    }
}
